package com.zl.user.service.impl;

import com.zl.basic.constant.VerifyConstants;
import com.zl.basic.exception.BusinessException;
import com.zl.basic.service.impl.BaseServiceImpl;
import com.zl.basic.util.MD5Utils;
import com.zl.basic.util.StrUtils;
import com.zl.user.domain.LoginInfo;
import com.zl.user.domain.User;
import com.zl.user.dto.UserDto;
import com.zl.user.mapper.LoginInfoMapper;
import com.zl.user.mapper.UserMapper;
import com.zl.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
   @Autowired
   private RedisTemplate redisTemplate;

   @Autowired
   private LoginInfoMapper loginInfoMapper;

   @Autowired
   private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(UserDto userDto) {
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        // 1.空值校验
        if (StringUtils.isEmpty(password)||StringUtils.isEmpty(passwordRepeat)||
                StringUtils.isEmpty(phone)|| StringUtils.isEmpty(phoneCode)){
        throw new BusinessException("数据不能为空");
        }

        // 2.密码一致校验
        if (!password.trim().equals(passwordRepeat.trim())){
            throw new BusinessException("前后密码不一致");
        }

        // 校验验证码是否过期
        Object redisPhoneCode = redisTemplate.opsForValue().get(VerifyConstants.REGISTER_PREFIX + phone);
        if (redisPhoneCode==null){
            throw new BusinessException("手机验证码失效");
        }
        //校验手机验证码是否正确
        if (!redisPhoneCode.toString().split(":")[0].equalsIgnoreCase(phoneCode)){
            throw new BusinessException("手机验证码错误");
        }
        //5.添加-t_logininfo信息
        User user = userDto2user(userDto);
        LoginInfo logininfo = user2Logininfo(user);
        loginInfoMapper.save(logininfo);

        //6.添加-t_user信息
        user.setLogininfo_id(logininfo.getId());
        userMapper.save(user);


    }

    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        // 1.空值校验
        if (StringUtils.isEmpty(password)||StringUtils.isEmpty(passwordRepeat)||
                StringUtils.isEmpty(email)){
            throw new BusinessException("数据不能为空");
        }

        // 2.密码一致校验
        if (!password.trim().equals(passwordRepeat.trim())){
            throw new BusinessException("前后密码不一致");
        }

        //3.判断邮箱是否被注册
        User user1 = userMapper.loadByEmail(email);
        if (user1!=null){
            throw new BusinessException("邮箱已经被注册，请直接登录！！！");
        }

        //4.添加-t_logininfo信息
        User user = userDto3user(userDto);
        LoginInfo logininfo = user3Logininfo(user);
        loginInfoMapper.save(logininfo);

        //5.添加-t_user信息
        user.setLogininfo_id(logininfo.getId());
        userMapper.save(user);

        //用户激活
        //3.发送邮件：审核通过邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("747485784@qq.com");
        //设置主题
        helper.setSubject("邮箱注册激活邮件");
        //设置内容
        helper.setText("<h1>你已经注册成功!!!</h1>" +
                "<a href='http://localhost:8080/user/emailActivation/"+user.getId()+"'>点击该链接激活</a>",true);
        //设置收件人
        //helper.setTo(employee.getEmail());
        helper.setTo("2736920793@qq.com");
        //发送
        javaMailSender.send(mimeMessage);


    }

    private LoginInfo user3Logininfo(User user) {

        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user,loginInfo);
        loginInfo.setType(1);
        loginInfo.setDisable(false);
        return loginInfo;
    }

    private User userDto3user(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getEmail());
        user.setEmail(userDto.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        user.setState(0);
        String md5 = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5);
        return user;

    }

    private LoginInfo user2Logininfo(User user) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user,loginInfo);
        loginInfo.setType(1);
        return loginInfo;

    }

    private User userDto2user(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);

        String md5 = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5);
        return user;
    }


    @Override
    public void save(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5PWD = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5PWD);
        LoginInfo loginInfo = user2Logininfo(user);
        loginInfoMapper.save(loginInfo);
        super.save(user);
    }


    @Override
    public void remove(Long id) {
        Long logininfo_id = userMapper.loadById(id).getLogininfo_id();
        loginInfoMapper.remove(logininfo_id);
        super.remove(id);
    }

    @Override
    public void update(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5PWD = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5PWD);
        Long logininfo_id = userMapper.loadById(user.getId()).getLogininfo_id();
        LoginInfo loginInfo = user2Logininfo(user);
        loginInfo.setId(logininfo_id);
        loginInfoMapper.update(loginInfo);

        super.update(user);
    }
}
